package com.lee.common.di

import com.lee.common.BuildConfig
import com.lee.common.network.BaseResp
import com.lee.common.network.LiveDataCallAdapterFactory
import com.lee.common.utils.accessToken
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Singleton


//const val BASE_URL = "https://amoeba.hinnotek.com/amoeba/"
const val BASE_URL = "http://192.168.4.10:8012/amiba/"
//const val BASE_URL = "http://192.168.4.115:8080/"

//app/inventoryWarehouse/getSysWarehouseListByUserId

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Singleton
    @Provides
    fun provideRetrofit(okHttp: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttp)
            .addCallAdapterFactory(LiveDataCallAdapterFactory { code, msg, obj ->
                BaseResp(code, msg, obj)
            })
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Provides
    fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
        val builder = OkHttpClient.Builder()
        builder.retryOnConnectionFailure(true) //连接失败后是否重新连接
            .connectTimeout(60, TimeUnit.SECONDS) //超时时间60S
            .writeTimeout(120, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .addNetworkInterceptor(loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY))
            .addInterceptor(Interceptor { chain ->
                val request = chain.request()
                    .newBuilder()
                    .addHeader("token", accessToken)
                    .build()
                chain.proceed(request)
            })
        return builder.build()
    }

    @Provides
    fun provideLoggingInterceptor(): HttpLoggingInterceptor {
        return HttpLoggingInterceptor { message ->
            if (BuildConfig.DEBUG) {
                Timber.e("OkHttp====Message:$message")
            }
        }
    }
}